#include <QAction>
#include <QPainter>
#include <QPen>

#include "listbutton.h"

ListButton::ListButton(QWidget *parent, int listOffset, QString name) :
    QPushButton(parent)
{
    this->listOffset = listOffset;
    this->name = name;
    this->isHead = false;
    this->isTail = false;
    this->isAfterChecked = false;
    QObject::connect( this, SIGNAL(clicked()), this, SLOT(send()) );

    QAction *ac = new QAction( "delete", this );
    QObject::connect( ac, SIGNAL(triggered()), this, SLOT(delList()) );
    this->addAction( ac );

    this->setContextMenuPolicy(Qt::ActionsContextMenu);
    this->setAutoExclusive(true);
    this->setCheckable(true);
    this->setAutoFillBackground(true);

    this->setObjectName(name);
    this->setToolTip(name);
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    this->setSizePolicy(sizePolicy);
}

void ListButton::paintEvent( QPaintEvent * )
{
    QPainter painter(this);

    QBrush brush(QColor(230, 230, 230));
    brush.setStyle(Qt::Dense3Pattern);

    if(this->isChecked()){
        brush.setColor(QColor(250, 250, 250));
        brush.setStyle(Qt::Dense1Pattern);
    }

    painter.fillRect(0, 0, this->width(), this->height(), brush);

    QTextOption to(Qt::AlignCenter);
    painter.drawText(this->rect(), this->name, to);

    painter.setPen(Qt::gray);

    QLine checkedLines[] = {
        QLine( 0, 0, this->width(), 0 ),
        QLine( 0, 0, 0, this->height() ),
        QLine( 0, this->height()-1, this->width(), this->height()-1 )
    };
    QLine unCheckedLines[] = {
        QLine( 0, 0, this->width(), 0 ),
        QLine( 0, 0, 0, this->height() ),
        QLine( 0, this->height()-1, this->width(), this->height()-1 ),
        QLine( this->width()-1, 0, this->width()-1, this->height() )
    };
    QLine afterCheckedLines[] = {
        QLine( 0, 0, this->width(), 0 ),
        QLine( 0, 0, 0, this->height() ),
        QLine( 0, this->height()-1, this->width(), this->height()-1 ),
        QLine( this->width()-1, 0, this->width()-1, this->height() )
    };

    if(this->isChecked())
        painter.drawLines( &checkedLines[0], sizeof(checkedLines) / sizeof(QLine) );
    else if(this->isAfterChecked)
        painter.drawLines( &afterCheckedLines[0], sizeof(afterCheckedLines) / sizeof(QLine) );
    else
        painter.drawLines( &unCheckedLines[0], sizeof(unCheckedLines) / sizeof(QLine) );


}

void ListButton::send()
{
    emit list_clicked( listOffset );
}

void ListButton::delList()
{
    emit list_delete( listOffset );
}

void ListButton::setIsHead(bool is)
{
    this->isHead = is;
}

void ListButton::setIsTail(bool is)
{
    this->isTail = is;
}

void ListButton::setIsAfterChecked(bool is)
{
    this->isAfterChecked = is;
}
